import axios from 'axios';
import { showStatus } from './error.js';
import { ElLoading, ElMessage } from 'element-plus';
// 封装公共请求方法
class ZxRequest {
	constructor(config) {
		// 创建axios实例
		this.instance = axios.create(config);
		// 保存基本信息
		this.interceptors = config.interceptors;
		this.showLoading = config.showLoading || true;
		//实例请求拦截
		this.instance.interceptors.request.use(this.interceptors.requestInterceptor, this.interceptors.requestInterceptorCatch);
		//所有请求拦截
		this.instance.interceptors.request.use(
			(config) => {
				// console.log('请求成功拦截-所有')
				if (this.showLoading) {
					this.loading = ElLoading.service({
						lock: true,
						text: '加载中...',
						background: 'rgba(0, 0, 0, 0)',
					});
				}
				return config;
			},
			(err) => {
				// console.log('请求失败拦截-所有')
				return err;
			}
		);
		//所有响应拦截
		this.instance.interceptors.response.use(
			(res) => {
				// console.log('响应成功拦截-所有')
				if (this.loading) {
					this.loading.close();
				}
				const status = res.status;
				let msg;
				if (status < 200 || status >= 300) {
					msg = showStatus(status);
					if (typeof res.data === 'string') {
						res.data = { msg };
					} else {
						res.data.msg = msg;
					}
					ElMessage({
						message: msg,
						type: 'error',
					});
				}
				return res.data;
			},
			(err) => {
				// console.log('响应失败拦截-所有')
				if (this.loading) {
					this.loading.close();
				}
				let status;
				if (err.message.indexOf('timeout') !== -1) {
					status = 504;
				} else {
					status = err.message.replace(/[^\d]/g, ' ');
				}
				if (status < 200 || status >= 300) {
					ElMessage({
						message: showStatus(status),
						type: 'error',
					});
				}
				return err;
			}
		);
		//实例响应拦截
		this.instance.interceptors.response.use(this.interceptors.responseInterceptor, this.interceptors.responseInterceptorCatch);
	}
	request(config) {
		return new Promise((resolve, reject) => {
			if (config.loading === false) {
				this.showLoading = config.loading;
			}
			this.instance
				.request(config)
				.then((res) => {
					this.showLoading = true;
					resolve(res);
				})
				.catch((err) => {
					this.showLoading = true;
					reject(err);
					return err;
				});
		});
	}
	get(config) {
		return this.request({
			...config,
			method: 'get',
		});
	}
	post(config) {
		return this.request({
			...config,
			method: 'post',
		});
	}
}

export default ZxRequest;
